package com.naizhuai.ui.task;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.TaskActionApiStore;
import com.naizhuai.network.exception.ValidateException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.SpacesItemDecoration;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.entity.Bus.Bus;
import com.naizhuai.ui.entity.Task.AddTaskFlowPage;
import com.naizhuai.ui.entity.Task.FlowMethodDetial;
import com.naizhuai.ui.entity.Task.UploadFlow;
import com.naizhuai.ui.entity.UserLeader;
import com.naizhuai.ui.task.adapter.StepListAdapter;
import com.naizhuai.ui.task.adapter.TaskTypeAdapter;
import com.naizhuai.ui.task.deliverentity.TaskDetial;
import com.naizhuai.ui.task.deliverentity.TaskType;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.RxBus;
import com.naizhuai.util.ViewUtils;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

public class FlowSettingActivity extends BaseActivity {
    private static String TaskDetial="taskDetial";
    @BindView(R.id.taskname)
    TextView taskname;
    @BindView(R.id.taskcycle)
    TextView taskcycle;
    @BindView(R.id.task_leader)
    CircleImageView taskLeader;
    @BindView(R.id.btn_flow_add)
    Button btnFlowAdd;
    @BindView(R.id.btn_plan_release)
    Button btnPlanRelease;
    @BindView(R.id.flowRecycleList)
    RecyclerView flowRecycleList;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.step_selector)
    RecyclerView stepSelector;
    private TaskTypeAdapter mStepAdapter;
    private TaskDetial mTaskDetial;
    private FlowMethodDetial mFlowMethodDetial;
    private int flowCount;
    public static void start(Context context, @NonNull TaskDetial taskDetial) {
        Intent intent = new Intent(context, FlowSettingActivity.class);
        intent.putExtra(TaskDetial,taskDetial);
        context.startActivity(intent);
    }
    private StepListAdapter mStepListAdapter;
    private TaskActionApiStore mTaskActionApiStore;
    public List<TaskType> circleTypeList;
    public List<UserLeader> managerList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    private void initData() {
        if (mTaskActionApiStore == null) {
            mTaskActionApiStore = TaskActionApiIml.getInstance();
        }
        mTaskDetial=(TaskDetial)getIntent().getSerializableExtra(TaskDetial);
        if (mTaskDetial!=null){
            taskname.setText(getString(R.string.task_name_format,mTaskDetial.taskName));
            taskcycle.setText(getString(R.string.task_cycle_show,mTaskDetial.taskCycle));
            taskLeader.post(new Runnable() {
                @Override
                public void run() {
                    ViewUtils.showAvatorOrName(mTaskDetial.managerthumb,mTaskDetial.manageName,taskLeader);
                }
            });
            mTaskActionApiStore.add_task_flow_page(mTaskDetial.taskid, AccountHelper.getComPanyid())
                               .subscribe(new NetWorkObserver<AddTaskFlowPage>() {
                                   @Override
                                   protected void onFail(String errormsg) {
                                       shortToast(getString(R.string.action_fail));
                                   }

                                   @Override
                                   protected void onSuccess(AddTaskFlowPage result) {
                                       mStepAdapter.setTypeList(result.methodList);
                                       //默认点击第一个
                                       circleTypeList=result.circleTypeList;
                                       managerList=result.managerList;
                                       result.methodList.get(0).setSelected(true);
                                       defaultFirst(result.methodList.get(0).getValue());
                                   }
                               });
        }
    }
    //默认选择第一个
    private void defaultFirst(String value) {
        mTaskActionApiStore.task_flow_method_detail(value)
                .subscribe(new NetWorkObserver<List<FlowMethodDetial>>() {
                    @Override
                    protected void onFail(String errormsg) {
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(List<FlowMethodDetial> result) {
                        genernewAdapter(result);
                        flowCount=result.size();
                        mFlowMethodDetial=result.get(0).clone();

                    }
                });
    }

    private void genernewAdapter(List<FlowMethodDetial> result) {
        mStepListAdapter=new StepListAdapter();
        mStepListAdapter.setFlowList(result);
        mStepListAdapter.setTypeData(circleTypeList,managerList);
        flowRecycleList.setAdapter(mStepListAdapter);
    }

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
        flowRecycleList.setLayoutManager(new LinearLayoutManager(this));
        flowRecycleList.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.padding_default_min)));
        flowRecycleList.setAdapter(mStepListAdapter = new StepListAdapter());

        mStepAdapter = new TaskTypeAdapter();
        stepSelector.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        stepSelector.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.constraint_default), LinearLayoutManager.HORIZONTAL));
        stepSelector.setAdapter(mStepAdapter);
        mStepAdapter.getSelectedClicks().subscribe(type -> {
            //请求接口 获取对应对数据
            mTaskActionApiStore.task_flow_method_detail(type.getValue())
                    .subscribe(new NetWorkObserver<List<FlowMethodDetial>>() {
                        @Override
                        protected void onFail(String errormsg) {
                            shortToast(errormsg);
                        }

                        @Override
                        protected void onSuccess(List<FlowMethodDetial> result) {
                            genernewAdapter(result);
                            flowCount=result.size();
                            mFlowMethodDetial=result.get(0).clone();
                        }
                    });
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_flow_setting;
    }

    @OnClick(R.id.btn_flow_add)
    public void onBtnFlowAddClicked() {
        if (mFlowMethodDetial!=null){
            mFlowMethodDetial.step=String.valueOf(++flowCount);
            mStepListAdapter.addFlow(mFlowMethodDetial);
        }
//        flowRecycleList.smoothScrollToPosition();
    }

    @OnClick(R.id.btn_plan_release)
    public void onBtnPlanReleaseClicked() {
        try{
            List<UploadFlow> uploadFlows= mStepListAdapter.getUploadFlow(this);
            //先通过遍历 得到是从本地选取的图片 然后按顺序保存对象 然后压缩图片 然后上传图片
            showWaitDiaLog();
            mTaskActionApiStore.add_task_flow(mTaskDetial.taskid,new Gson().toJson(uploadFlows))
                               .subscribe(new NetWorkObserver<String>() {
                                   @Override
                                   protected void onFail(String errormsg) {
                                       hideWaitDialog();
                                       shortToast(errormsg);
                                   }
                                   @Override
                                   protected void onSuccess(String result) {
                                       hideWaitDialog();
                                       if ("0".equals(result)){
                                           shortToast(getString(R.string.sendfail));
                                       } else {
                                           shortToast(getString(R.string.addtaskflow_success));
                                           finish();
                                           RxBus.getDefault().postSticky(new Bus.ReFreshTask());
                                       }
                                   }
                               });
        }catch (ValidateException e){
            shortToast(e.getMessage());
        }catch (Exception e){
            shortToast(getString(R.string.exist_wait_input_msg));
        }
    }

    @Override
    public void onBackPressedWithoutDialog() {
        DialogUtils.showSureDialog(this, getString(R.string.lost_data), dialog -> finish());
    }

}
